#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <ctime>
using namespace std;

#include <folly/init/Init.h>
#include <folly/futures/Future.h>
#include <folly/executors/GlobalExecutor.h>

folly::Future<int> foo(int arg)
{
    cout << "foo(" << arg << ")"
         << " in thread[" << std::this_thread::get_id() << "]" << endl;
    auto promise = std::make_shared<folly::Promise<int>>();
    promise->setValue(arg);
    return promise->getFuture();
}

folly::Future<folly::Unit> bar(int arg)
{
    cout << "bar(" << arg << ")"
         << " in thread[" << std::this_thread::get_id() << "]" << endl;
    return folly::makeFuture();
}

int main(int argc, char *argv[])
{
    folly::Init init(&argc, &argv);

    cout << "making promise in thread[" << std::this_thread::get_id() << "]" << endl;

    folly::Promise<int> p;
    folly::Future<int> f = p.getFuture();
    f.via(folly::getCPUExecutor().get()).thenValue(foo).thenValue(bar);

    cout << "future chain made in thread[" << std::this_thread::get_id() << "]" << endl;

    std::thread t([&p]()
                  {
        cout << "promise filling in thread[" << std::this_thread::get_id() << "]" << endl;
        p.setValue(int(std::time(nullptr)));
        cout << "promise filled in thread[" << std::this_thread::get_id() << "]" << endl; });

    t.join();

    while (true)
    {
        if (f.isReady() && f.hasValue())
        {
            cout << "f.value()=[" << f.value() << "]" << endl;
            break;
        }
    }

    // std::this_thread::sleep_for(500ms);

    // cout << "finished" << endl;

    // getchar();

    return 0;
}
